We've moved! — MindVault360 is now HexLab. Better design, more content & premium notes.

Visit HexLab →

MindVault360 has moved!

We've upgraded to HexLab — a faster, more professional platform with better content, premium notes, and a modern design.

Visit us at hexlab

Wednesday, September 11, 2024

Synchronization in Java

 

(Tap the post to see more)


Synchronization in Java is the capability to control the access of multiple threads to any shared resource. It is a technique through which we can control multiple threads or among no of threads only one thread will enter the synchronized area.

Example 01:


package com.java.Multi_threading;

// A Sender class

class Sender

{

public void SenderMsg(String msg)

{

System.out.println("\nSending a Message: " + msg);

try

{

Thread.sleep(800);

}

catch (Exception e)

{

System.out.println("Thread interrupted.");

}

System.out.println("\n" +msg+ "Sent");

}

}

// A Sender class for sending a message using Threads

class SenderWThreads extends Thread

{

private String msg;

Sender sd;

// Receiver method to receive a message object and a message to be sent

SenderWThreads(String m, Sender obj)

{

msg = m;

sd = obj;

}

public void run()

{

// Checks that only one thread sends a message at a time.

synchronized(sd)

{

// synchronizing the sender object

sd.SenderMsg(msg);

}

}

}

// Driver Code

public class ShynchronizedMultithreading

{

public static void main(String args[])

{

Sender sender = new Sender();

SenderWThreads sender1 = new SenderWThreads( "Hola " , sender);

SenderWThreads sender2 = new SenderWThreads( "Welcome to Programming ", sender);

// Start two threads of SenderWThreads type

sender1.start();

sender2.start();

// wait for threads to end

try

{

sender1.join();

sender2.join();

}

catch(Exception e)

{

System.out.println("Interrupted");

}

}

}



Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific resource of the method.

Example 02:


package com.java.Multi_threading;

//example of java synchronized method

class Tables{

synchronized void printTable(int n){//synchronized method

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

}

}

}

class MyThreads_1 extends Thread{

Tables t;

MyThreads_1(Tables t){

this.t=t;

}

public void run(){

t.printTable(5);

}

}

class MyThreads_2 extends Thread{

Tables t;

MyThreads_2(Tables t){

this.t=t;

}

public void run(){

t.printTable(100);

}

}

public class TestSynchronization2{

public static void main(String args[]){

Table obj = new Table();//only one object

MyThread1 t1=new MyThread1(obj);

MyThread2 t2=new MyThread2(obj);

t1.start();

t2.start();

}

}

← Back Next →

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home